package com.llsly.wearabledataviz.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Component
public class WebSocketTestPush {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    private Random random = new Random();
    private String[] stages = {"深睡", "浅睡", "快速眼动", "清醒"};

    @Scheduled(fixedRate = 3000) // 每3秒推送一次多类型数据
    public void pushMockData() {
        int heartRate = 60 + random.nextInt(40);
        int steps = 1000 + random.nextInt(5000);
        double sleepDuration = Math.round((4 + random.nextDouble() * 4) * 100.0) / 100.0;
        boolean isAnomaly = heartRate > 100 || heartRate < 60;
        String anomalyDescription = null;
        if (heartRate > 100) anomalyDescription = "心率过高";
        if (heartRate < 60) anomalyDescription = "心率过低";

        Map<String, Object> data = new HashMap<>();
        data.put("heartRate", heartRate);
        data.put("steps", steps);
        data.put("sleepDuration", sleepDuration);
        data.put("timestamp", LocalDateTime.now().toString());
        data.put("isAnomaly", isAnomaly);
        data.put("anomalyDescription", anomalyDescription);

        messagingTemplate.convertAndSend("/topic/wearable-data", data);
    }

    @Scheduled(fixedRate = 60000) // 每分钟推送一次睡眠阶段
    public void pushSleepStage() {
        String stage = stages[random.nextInt(stages.length)];
        Map<String, Object> data = new HashMap<>();
        data.put("timestamp", LocalDateTime.now().toString());
        data.put("sleepStage", stage);
        messagingTemplate.convertAndSend("/topic/sleep-stage", data);
    }
} 